<template>
  <basic-container>
    <avue-crud v-model="form" v-bind="bindVal" :page.sync="page" v-on="onEvent">
      <template slot="menu" slot-scope="{type,size,row}">
        <el-button icon="el-icon-document" :size="size" :type="type" @click="toDetail(row)">详情</el-button>
        <el-button icon="el-icon-edit" :size="size" :type="type" @click="toEdit(row, index)">编辑</el-button>
        <el-button icon="el-icon-delete" :size="size" :type="type" @click="toDelete(row, index)">删除</el-button>

      </template>
      <template slot="file" slot-scope="{type,size,row}">
        <el-button icon="el-icon-download" :size="size" :type="type" :disabled="row.state == 0"
          @click="createArchive(row)">生成卷宗</el-button>
      </template>
      <template slot="menuLeft" slot-scope="{size}">
        <el-button type="primary" :size="size" @click="startRegister">受案登记</el-button>
        <el-button type="info" disabled :size="size">导出</el-button>
        <el-button type="info" :size="size" @click="showImportDialog">导入</el-button>
        <el-button type="info" disabled :size="size">导入模块下载</el-button>
      </template>
      <template slot="fireAddressForm" slot-scope="{row}">
        <div class="map-input-box">
          <el-input v-model="addressText" type="text" placeholder="请输入" />
          <div class="map-select-box">
            <el-button class="map-select-btn" type="primary">选择地址</el-button>
            <avue-input-map class="map" :params="{ zoom: 10 }" placeholder="请选择地图"
              v-model="formatAddress"></avue-input-map>
          </div>
        </div>
      </template>
      <template slot="state" slot-scope="{row}">
        <el-tag v-if="row.state === '0'" type="danger" size="mini">{{ row.$state }}</el-tag>
        <el-tag v-else size="mini" type="primary">{{ row.$state }}</el-tag>
      </template>
      <template slot="archivesType" slot-scope="{row}">
        <el-tag :type="typeArr[row.archivesType]" size="mini">{{ row.$archivesType }}</el-tag>
      </template>
      <template slot="coordinationForm" slot-scope="{row}">
        <el-button type="primary">协同办案</el-button>
      </template>
    </avue-crud>

    <el-dialog :visible.sync="open" width="80%" append-to-body>
      <div class="archiver_container">
        <div class="HXIframe" style='margin-top: -105px;margin-left: -238px'>
          <iframe ref="addIframe2" width="100%" height="700"
            src="http://112.124.244.72/#/xfjd/hzdc/hzxxdj/djhzxx?runId=-1" frameborder="0" />
        </div>
      </div>
    </el-dialog>
    <import-dialog-com v-model="importDialog" @refresh="getList" />
  </basic-container>
</template>

<script>
// import { getPage, loginInSuprvision } from '@/api/supervision/index'
import { listUser } from '@/api/system/user'
import xmldom from 'xmldom'
import ImportDialogCom from './components/importDialog'

export default window.$crudCommon(
  {
    name: 'Archives',
    components: { ImportDialogCom },
    data() {
      return {
        open: false,
        archivesId: '',
        typeArr: ['success', 'primary', 'warning'],
        importDialog: false,
      }
    },
    computed: {
      iframeSrc() {
        return `${process.env.VUE_APP_H5_API}/imageAssociation?token=${this.$store.getters.token}&archivesId=${this.archivesId}`
      },
      formatAddress: {
        get() {
          if (!this.form.fireAddress) return []
          if (this.form.fireAddress && !this.form.fireAddress.length) return []
          return this.form.fireAddress.split(',')
        },
        set(val) {
          console.log(val);
          if (!val.length) return
          this.form.fireAddress = val.join(',')
        }
      },
      addressText: {
        get() {
          if (!this.form.fireAddress) return ''
          if (this.form.fireAddress && !this.form.fireAddress.length) return ''
          return this.form.fireAddress.split(',')[2]
        },
        set(val) {
          let address = this.form.fireAddress.split(',')
          address[2] = val
          this.form.fireAddress = address.join(',')
        }
      }
    },
    created() {
      window.addEventListener('message', this.receiveMessage, false)
      // window.addEventListener('popstate', () => {
      //   console.log(2222)
      // })

      // const hxToken = getHxToken()
      // if (!hxToken) {
      //   const formData = new URLSearchParams()
      //   const pwd = md5('root@123456')
      //   formData.append('tenantId', '000000')
      //   formData.append('username', 'gaoyb@zj')
      //   formData.append('password', pwd)
      //   formData.append('type', 'account')
      //   formData.append('grant_type', 'captcha')
      //   formData.append('scope', 'all')
      //   axios({
      //     url: '/hxapi/api/blade-auth/oauth/token',
      //     headers: {
      //       Authorization: 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
      //       'Content-Type':
      //         'application/x-www-form-urlencoded',
      //       'Tenant-Id': '000000'
      //     },
      //     method: 'post',
      //     data: formData
      //   })
      //     .then(hxRes => {
      //       setHxToken(hxRes.data.access_token)
      //       sessionStorage.setItem(
      //         'SET_HX_INFO',
      //         JSON.stringify(hxRes.data)
      //       )

      //       localStorage.setItem(
      //         'xfjd-token',
      //         JSON.stringify({
      //           content: hxRes.data.access_token,
      //           dataType: "string",
      //           datetime: 1663554462782
      //         })
      //       )
      //     })
      //     .catch(error => { })
      // }
    },
    destroyed() {
      window.removeEventListener('message', this.receiveMessage, false)
    },
    mounted() {
      listUser({ page: 1, pageSize: 999 }).then(res => {
        const data = res.rows.map(item => ({ label: item.nickName, value: item.userId, dept: item.dept.deptName }))
        const doOtherPersonColumn = this.findObject(this.option.column, 'doOtherPerson')
        const doPersonColumn = this.findObject(this.option.column, 'doPerson')
        doPersonColumn.dicData = doOtherPersonColumn.dicData = data
      })
      // console.log()
      // this.getPageData()
    },
    methods: {
      toEdit(row, index) {
        this.$refs.crud.rowEdit(row, index)
      },
      toDelete(row, index) { this.$refs.crud.rowDel(row, index) },
      showImportDialog() {
        this.importDialog = true
        // this.getImportHxData()
      },
      startRegister() {
        this.openwindow('http://112.124.244.72/#/xfjd/hzdc/hzxxdj/djhzxx?runId=-1', '', 1200, 800)
      },
      getPageData() {
        return getPage().then(res => {
          // window.open(res)
          const dom = new xmldom.DOMParser().parseFromString(res, 'text/html')
          const list = dom.getElementsByTagName('table')[2].getElementsByTagName('tr')
          const data = []
          console.log(this.importOption.column)
          for (let index = 1; index < list.length; index++) {
            // console.log(list[index])
            const tdArr = list[index].getElementsByTagName('td')
            const obj = {}
            for (let i = 0; i < tdArr.length; i++) {
              if (this.importOption.column[i]) {
                obj[this.importOption.column[i].prop] = tdArr[i].textContent.trim()
              }
            }
            obj.callTime = obj.callTime + ' 00:00:00'
            obj.archivesType = '0'
            const arr = obj.doPerson.split('(主)、')
            obj.doPerson = arr[0]
            obj.doOrg = arr[0]
            obj.doOtherPerson = arr[1]
            obj.doOrg = this.$store.state.user.deptName
            data.push(obj)
          }
          this.importData = data
        }).catch(() => {
          loginInSuprvision().catch(this.getPageData)
        })
      },
      toDetail(row) {
        this.$router.push({
          path: '/Marchives/archive-detail/detail',
          query: {
            archivesId: row.archivesId
          }
        })
      },
      async createArchive(row) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        let res = await this.api.downloadPdf(row.archivesId)
        loading.close();
        this.openwindow(res.data.pdfPath, '', 1200, 800)
      }
    }
  },
  {
    name: 'archives/archives',
    rowKey: 'archivesId',
    data: 'rows'
  }
)
</script>
<style lang="scss" scoped>
.HXIframe {
  z-index: 11111;
  top: 0;
  left: 0;
  background-color: #fff;
}

.archiver_container {
  overflow: hidden;
}

.map-input-box {
  display: flex;

  .map-select-box {
    position: relative;
    cursor: pointer;
    margin-left: 10px;
    overflow: hidden;
    min-width: 80px;

    .map {
      position: absolute;
      right: 0;
      top: 0;
      opacity: 0;
      cursor: pointer;
      height: 100%;

      ::v-deep .el-textarea__inner {
        cursor: pointer;
      }
    }
  }
}
</style>
